import algoliasearch from 'algoliasearch';
import algoliasearchHelper from 'algoliasearch-helper';

const client = algoliasearch('{{appId}}', '{{apiKey}}');
const helper = algoliasearchHelper(client, '{{indexName}}');

const $searchBox = document.querySelector('#searchBox input[type=search]');
const $hits = document.querySelector('#hits');

$searchBox.addEventListener('input', event => {
  const query = event.target.value;

  helper.setQuery(query).search();
});

helper.on('result', ({ results }) => {
  // Please sanitize user-provided data when using `innerHTML` to avoid XSS
  $hits.innerHTML = `
    <ol class="ais-hits">
      ${results.hits
        .map(
          hit =>
            `<li class="ais-hits--item">
              <article>
              {{#if attributesToDisplay}}
                {{#if imageAttribute}}
                <img src="${ hit.{{imageAttribute}} }" alt="${ hit.{{attributesToDisplay.[0]}} }" />
                {{/if}}
                <div>
                  <h1>${hit._highlightResult.{{attributesToDisplay.[0]}}.value}</h1>
                  {{#each attributesToDisplay}}
                  {{#unless @first}}
                  <p>${hit._highlightResult.{{this}}.value}</p>
                  {{/unless}}
                  {{/each}}
                </div>
              {{else}}
                <p>
                  <code>${JSON.stringify(hit).slice(0, 100)}...</code>
                </p>
              {{/if}}
              </article>
            </li>`
        )
        .join('')}
    </ol>`;
});

helper.search();
